import { _decorator, Component, Node, Prefab, instantiate, Vec3, view, UITransform, v3 } from 'cc';
import { Item } from './Item';
import { ItemType, GameEventType, GameOverType } from '../Event/EnumDefine';
import { EventManager } from '../Event/EventManager';
import { BuffDataType, DataConfig } from '../Config/DataConfig';
import { tween } from 'cc';
import { SoundManager, SoundType } from '../SoundManager';
import Common from '../Config/Common';
import { ItemAttribute } from './ItemAttribute';
const { ccclass, property } = _decorator;

/** 道具物品类型 */
type ItemDropType = {
    type: ItemType,
    buff: BuffDataType,
    item: Node
}
/** 强化道具生成器 */
@ccclass('ItemSpawner')
export class ItemSpawner extends Component {
    @property(Prefab)
    trajectoryPrefab: Prefab; // 增加弹道道具

    @property(Prefab)
    actPrefab: Prefab; // 攻击力道具

    @property(Prefab)
    bombPrefab: Prefab; // 爆炸弹道具

    @property(Prefab)
    uziPrefab: Prefab; // 乌兹道具

    @property(Prefab)
    winPrefab: Prefab; // 胜利道具

    @property(Node)
    flyStartNode: Node; // 道具开始飞的起始位置的节点

    @property(Node)
    flyEndNode: Node; // 道具要飞到终点位置的节点

    private itemSpeed = 0;
    private dropList: ItemDropType[] = [];
    private dropLevel: number = -1;
    private isFinishDrop: boolean = false;// 掉落完成（最后的win道具掉落）
    private availableItems: { [type: number]: BuffDataType[] } = {}; // 当前可用的物品

    protected onLoad(): void {
        // 初始化各个道具的当前等级
        EventManager.instance.registerEvent(GameEventType.Drop_Init, this.onDropInit, this);
        EventManager.instance.registerEvent(GameEventType.Drop_Item, this.onDropItem, this);
        EventManager.instance.registerEvent(GameEventType.Change_Roll_Speed, (speed: number) => {
            this.itemSpeed = speed;
        }, this);

        this.onScreen();
        EventManager.instance.registerEvent(GameEventType.Screen_Change, this.onScreen, this);
    }
    start() {
        this.initializeItems();
    }

    initializeItems() {
        this.availableItems = Common.instance.clone(DataConfig.itemLevelBuff);
        EventManager.instance.triggerEvent(GameEventType.Drop_Init, null);
    }

    onScreen() {
        const screenSize = Common.instance.getScreenSize();
        let flyStartNodeX = this.flyStartNode.position.x;
        let flyStartNodeY = screenSize.height * 0.5 - 100;
        this.flyStartNode.setPosition(v3(flyStartNodeX, flyStartNodeY))
        if (this.dropList.length == 0) {
            return;
        }
        let drop = this.dropList[0];
        drop.item.setPosition(this.flyStartNode.position);
    }

    // 取出掉落道具
    onDropInit() {
        if (this.isFinishDrop) {
            return;
        }

        let levelLength = Object.keys(this.availableItems).length;
        let getDrop = (dropLevel: number) => {
            for (let index = 0; index < levelLength; index++) {
                let level = (dropLevel + index) % levelLength;
                let list: BuffDataType[] = this.availableItems[level];
                if (list && list.length > 0) {
                    return level;
                }
            }
            return -1;
        };
        // 下一个道具
        this.dropLevel = (this.dropLevel + 1) % levelLength;
        this.dropLevel = getDrop(this.dropLevel);
        if (this.dropLevel < 0) {
            const type: ItemType = ItemType.WIN;
            const item = instantiate(this.winPrefab);
            item.getChildByName('light').active = false;
            this.dropList.push({ type: type, buff: null, item: item });
            item.setParent(this.node);
            item.setScale(v3(0, 0, 0));
            item.setPosition(this.flyStartNode.position);
            tween(item).to(0.25, { scale: v3(0.5, 0.5) }).start();
            this.isFinishDrop = true;
        }
        else {
            const type: ItemType = this.dropLevel;
            const buff: BuffDataType = this.availableItems[type].shift();
            const item = instantiate(this.getPrefabByType(type)); // 实例化道具
            item.getChildByName('light').active = false;
            const childItem = item.getChildByName('item');
            childItem.children.forEach((icon) => {
                icon.active = Number(icon.name) == buff.iconId;
            });
            this.dropList.push({ type: type, buff: buff, item: item });

            const com = item.addComponent(Item);
            com.type = type;
            com.buffData = buff;
            com.isFlyToPlayer = true;
            com.itemSpeed = this.itemSpeed;
            item.setParent(this.node);
            item.setScale(v3(0, 0, 0));
            item.setPosition(this.flyStartNode.position);
            tween(item).to(0.25, { scale: v3(0.5, 0.5) }).start();
        }
    }

    onDropItem() {
        if (DataConfig.isGameStop) {
            return;
        }
        this.onFlyItem();
    }

    // 随机道具，飞到玩家身上
    onFlyItem() {
        if (this.dropList.length == 0) {
            return;
        }
        const pMiddle = v3(0, 120);
        const drop = this.dropList.shift();
        if (drop.type == ItemType.WIN) {
            drop.item.removeFromParent();
            EventManager.instance.triggerEvent(GameEventType.Stop_Create_Block, null);
            EventManager.instance.triggerEvent(GameEventType.Game_Over, GameOverType.GameWin);
            return;
        }

        drop.item.getChildByName('light').active = true;
        tween(drop.item)
            .delay(0.25)
            .to(0.25, { position: pMiddle, scale: v3(1, 1) })
            .delay(1.0)
            .to(0.25, {}, {
                onUpdate: (target: Node, ratio: number) => {
                    const pFinish = v3(this.flyEndNode.position.x - 12, this.flyEndNode.position.y - 85);
                    const currentPos = new Vec3(
                        pMiddle.x + (pFinish.x - pMiddle.x) * ratio,
                        pMiddle.y + (pFinish.y - pMiddle.y) * ratio,
                    );
                    // 更新位置
                    target.setPosition(currentPos);
                    // 更新缩放
                    const scale = 1 - (0.8 * ratio); // 从1缩小到0.2
                    target.setScale(scale, scale, scale);
                }
            })
            .call(() => {
                // 播放终点节点的放大缩小动画
                if (!DataConfig.isGamePause && !DataConfig.isGameStop) {
                    this.playEndNodeAnimation();
                }
            })
            // 完全消失
            .to(0.2, { scale: new Vec3(0, 0, 0) })
            // 动画结束后的回调
            .call(() => {
                // 销毁道具节点
                if (!DataConfig.isGamePause && !DataConfig.isGameStop) {
                    drop.item.removeFromParent();
                    EventManager.instance.triggerEvent(GameEventType.Item_Buff, { itemType: drop.type, buffData: drop.buff, });
                }
            })
            .start();
    }

    getPrefabByType(type: ItemType): Prefab {
        if (type == ItemType.ACT) {
            return this.actPrefab;
        }
        else if (type == ItemType.Bomb) {
            return this.bombPrefab;
        }
        else if (type == ItemType.UZI) {
            return this.uziPrefab;
        }
        else {
            return this.trajectoryPrefab;
        }
    }

    private playEndNodeAnimation() {
        EventManager.instance.triggerEvent(GameEventType.Player_Glow_Effect, null);
        SoundManager.instance.playSound(SoundType.GetItem);
        const originalScale = this.flyEndNode.getScale();

        tween(this.flyEndNode)
            .set({ scale: originalScale })
            .to(0.1, {
                scale: new Vec3(
                    originalScale.x * 1.2,
                    originalScale.y * 1.2,
                    originalScale.z
                )
            }, {
                easing: 'cubicOut'
            })
            .to(0.1, { scale: originalScale }, {
                easing: 'cubicIn'
            })
            .start();
    }
}
